package redis

import (
	"db-sharding/system/constant"
	"db-sharding/system/log4go"
	"encoding/json"
	"fmt"
	"github.com/emirpasic/gods/maps/hashmap"
	"time"
)

type Park struct {
	DbName     string `json:"dbName"`
	ParkName   string `json:"parkName"`
	CreateTime int64
}

var RouteCache = *hashmap.New()

func init() {
	log4go.Info("初始化缓存容器")
}

func LoadAll() {
	hmap := HGetAll(constant.ParkRouteCache)
	now := time.Now().Unix()
	for key, val := range hmap {
		park := Park{}
		err := json.Unmarshal([]byte(val), &park)
		if err != nil {
			fmt.Println(err.Error())
		} else {
			park.CreateTime = now
			RouteCache.Put(key, park)
		}
	}
	//b, _ := RouteCache.ToJSON()

	//log4go.Info("加载全车场路由", string(b))
}

func LoadPark(lotCode string) *Park {
	result := HGet(constant.ParkRouteCache, lotCode)

	if len(result) > 0 {
		park := Park{}
		err := json.Unmarshal([]byte(result), &park)
		if err != nil {
			fmt.Println(err.Error())
			log4go.Error("加载车场路由失败，车场id:{}", lotCode)
			return nil
		} else {
			//本地缓存3分钟失效
			park.CreateTime = time.Now().Unix() + 3*60
			RouteCache.Put(lotCode, park)
			log4go.Info("加载车场路由", park)
			return &park
		}
	}
	log4go.Error("加载车场路由失败，车场id:{}", lotCode)
	return nil
}

func GetRoute(lotCode string) (string, error) {
	val, exist := RouteCache.Get(lotCode)
	if !exist {
		park := LoadPark(lotCode)
		if park != nil {
			return park.DbName, nil
		}
	} else {
		switch v := val.(type) {
		case Park:
			//86400
			if v.CreateTime < time.Now().Unix() {
				//过期了，重新获取
				go LoadPark(lotCode)
			}
			return v.DbName, nil
		}
	}
	return "", fmt.Errorf("无法获取车场[%s]路由", lotCode)
}
